<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/16
 * Time: 15:28
 */
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Session;
use think\Db;

class Purchase extends Common {
	/**
	 * 判断是否登录
	*/
	public function _initialize()
	{
		parent::_initialize();
	}
	
	/**
	 * 采购单首页
	 * Method Get
	 * @param string get.title 检索的字段
	 * @param string get.status 2 查看购买通过的产品
	 * @param string get.status 3 查看邮寄的产品
	 * @param string get.status 4 查看货已到的产品
	 * @return Array  result 查询结果
	 * @return string  title 检索的字段
	 * @return string  status 状态
	*/
	public function index()
	{
		$where = ['query'=>[]];
		$status = 0;
		$db = Db::table('purchase')
			->field(
					'product.pname,product.purchaseprice,product.cooperation,product.retailprice,
					business.linkman,business.id as bid,business.telephone,shop.address,purchase.number,
					purchase.describe,purchase.id,purchase.total,purchase.actualtotal,purchase.status,
					purchase.ordernumber,purchase.pmethod,purchase.date'
					)
			->join('product','purchase.pid = product.id','LEFT')
			->join('business','purchase.bid = business.id','LEFT')
			->join('shop','purchase.sid = shop.id','LEFT')
			->where('purchase.status','<>',0)
			->order('purchase.id desc')
			->group('ordernumber');
		if(!empty(input('get.status'))){
			//if(input('get.status') != 0){
			$db->whereNotIn('purchase.status',[0,5]);
			$where['query']['status'] = 2;
			//}
		}
		if(!empty(input('get.title'))){
			$title = trim(input('get.title'));
			$db->where('product.pname|business.linkman|shop.address|purchase.ordernumber','like',"%{$title}%");
			$where['query']['title'] = $title;
			$status = trim(input('get.status'));
			$where['query']['status'] = $status;
		}
		$result = $db->paginate(8,false,$where);
		return view('index',compact('result','title','status'));
	}
	/**
	 * 订单详情
	 * @param string get.ordernumber 订单号
	*/
	public function purchaseDetail()
	{
		$ordernumber = trim(input('get.ordernumber'));
		$result = Db::table('purchase')
			->field(
				'product.pname,product.purchaseprice,product.cooperation,product.retailprice,
					business.linkman,business.id as bid,business.telephone,shop.address,purchase.number,
					purchase.describe,purchase.id,purchase.total,purchase.actualtotal,purchase.status,
					purchase.ordernumber,purchase.pmethod,purchase.express,purchase.oddnumber'
			)
			->join('product','purchase.pid = product.id','LEFT')
			->join('business','purchase.bid = business.id','LEFT')
			->join('shop','purchase.sid = shop.id','LEFT')
			->where('purchase.ordernumber',$ordernumber)
			->where('purchase.status','<>',0)
			->order('purchase.id desc')
			->paginate(8);
		return view('purchasedetail',compact('result','ordernumber'));
	}
	/**
	 * 采购单详情
	 * Method Get
	 * @param string get.id 采购单id
	 * @param string get.status 采购单状态
	 * @return Array result 查询结果
	*/
	public function detail()
	{
		$result = Db::table('purchase')
				->join('product','purchase.pid = product.id','LEFT')
				->join('business','purchase.bid = business.id','LEFT')
				->join('shop','purchase.sid = shop.id','LEFT')
				->where('purchase.id',trim(input('get.id')))
				->find();
		$status = Db::table('purchase')->where('id',trim(input('get.id')))->value('status');
		$id = trim(input('get.id'));
		$result['image'] = json_decode($result['image']);
		return view('detail',compact('result','id','status'));
	}
	/**
	 * 修改采购数量
	 * Method Post
	 * @param string post.id
	 * @param string post.number
	 * @return json 修改成功  error 修改失败错误信息
	*/
	public function updateTotal()
	{
		if(Request()->isAjax()){
			try{
				Db::startTrans();
				$input['number'] = trim(input('post.number'));
				$id = trim(input('post.id'));
				$purchaseprice = trim(input('post.purchaseprice'));
				$input['total'] = $input['number'] * $purchaseprice;
				$result = Db::table('purchase')->where('id',$id)->update($input);
				if(!$result){
					throw new \PDOException('修改失败');
				}
				Db::commit();
				$success = ['success' => '修改成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error' => $e->getMessage()];
				return json($error);
			}
			
		}
	}
	
	/**
	 * 添加实际价格
	 * Method Post
	 * @param string post.id 采购单id
	 * @param string post.total 实际价格
	 * @return json  添加成功   error  添加失败错误信息
	*/
	public function total()
	{
		if(Request()->isAjax()){
			try{
				Db::startTrans();
				$id = input('post.id');
				$input['actualtotal'] = input('post.total')+0;
				$result = Db::table('purchase')->where('id',$id)->update($input);
				if(!$result){
					throw new \PDOException('添加失败');
				}
				Db::commit();
				$success = ['success'=>'添加成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	
	/**
	 * 删除采购单
	 * Method Post
	 * @param string post.id 采购单id
	 * @return json success 删除成功 error 删除失败
	 */
	public function delete()
	{
		if(Request()->isAjax()){
			try{
				Db::startTrans();
				$result = Db::table('purchase')->where('id',input('post.id'))->update(['status'=>0]);
				if(!$result){
					throw new \PDOException('删除失败');
				}
				Db::commit();
				$success = ['success' => '删除成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error' => $e->getMessage()];
				return json($error);
			}
		}
	}
	
	/**
	 * 货已到
	 * Method Post
	 * @param string post.id 订单id
	 * @return json success 操作成功  error 操作失败错误信息
	*/
	public function cargo()
	{
		if(Request()->isAjax()){
			try{
				Db::startTrans();
				$result = Db::table('purchase')->where('id',input('post.id'))->update(['status'=>4]);
				if($result){
					//获取订单信息
					$value = Db::table('purchase')->where('id',input('post.id'))->find();
					if($value){
						//获取库存信息
						$val = Db::table('inventory')->whereNull('postid')->where('sid',$value['sid'])->where('pid',$value['pid'])->find();
						//如果存在更新库存
						if($val){
							$val['number'] = $val['number']+$value['number'];
							$res = Db::table('inventory')->where('pid',$val['pid'])->where('sid',$value['sid'])->update(['number' => $val['number']]);
							if(!$res){
								throw new \PDOException('库存修改失败');
							}
						}else{
							//不存在，添加库存
							$res = Db::table('inventory')->insertGetId(['sid'=>$value['sid'],'bid'=>$value['bid'],'pid'=>$value['pid'],'number'=>$value['number']]);
							if(!$res){
								throw new \PDOException('插入库存失败');
							}
						}
					}else{
						throw new \PDOException('订单已失效');
					}
				}else{
					throw new \PDOException('订单凭证添加失败');
				}
				Db::commit();
				$success = ['success'=>'操作成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	/**
	 * 修改订单状态
	 * @param string  get.id 订单号
	 * @param string  get.status 订单状态
	 * @return json success 修改成功, error 修改失败错误信息
	*/
	public function updatestatus()
	{
		if(Request()->isAjax()){
			try{
				$id = input('post.id');
				$status = input('post.status');
				//字母 w 代表订单完成
				if($status == 'w'){
					$result = Db::table('purchase')->where('id',$id)->update(['status'=>5]);
					if(!$result){
						throw new \PDOException('操作失败');
					}
				}
				// 字母 t 代表购买通过
				if($status == 't'){
					$result = Db::table('purchase')->where('id',$id)->update(['status'=>2]);
					if(!$result){
						throw new \PDOException('操作失败');
					}
				}
				Db::commit();
				$success = ['success'=>'操作成功'];
				return json($success);
			}catch (\PDOException $e){
				Db::rollback();
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
	
	/**
	 * 添加物流信息页面
	 * @param string post.id 采购单id
	 */
	public function express()
	{
		$id = input('get.id');
		return view('express',compact('id'));
	}
	
	/**
	 * 添加快递公司
	 * @param string post.id 采购单id
	 * @param string post.express 快递公司
	*/
	public function logistics()
	{
		if(request()->isPost()){
			try{
				$id = input('post.id');
				$input['express'] = input('post.express');
				$input['oddnumber'] = input('post.oddnumber');
				$input['status'] = 3;
				$result = Db::table('purchase')->where('id',$id)->update($input);
				if(!$result){
					throw new \PDOException('添加失败');
				}
				$success = ['success'=>'添加成功'];
				return json($success);
			}catch (\PDOException $e){
				$error = ['error'=>$e->getMessage()];
				return json($error);
			}
		}
	}
}